package tau_sadna.tau_map;

import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;
import android.util.Xml;

public class LayerXmlParser {
	// We don't use namespaces
    private static final String ns = null;
    
    public ArrayList<TauLayer> permLayers = null;
    
    public LayerXmlParser(){}
    
    public MainActivity mainAct;
    
    // this function calls 'parse' and hoards results in  permLayers
    void init(MainActivity act){
    	mainAct = act;
    	
    	ArrayList<TauLayer> layers =  new ArrayList<TauLayer>();
    	
    	File dir_file = new File(act.getFilesDir()+"");
    	Log.i("LayerXmlParser", "Starting to parse directory "+dir_file.getAbsolutePath());
    	String[] myFiles = dir_file.list(new FilenameFilter() {
    	    public boolean accept(File directory, String fileName) {
    	        return fileName.endsWith(".lay");
    	    }
    	});
    	for(String file_name : myFiles){
    		Log.i("LayerXmlParser", "Parsing layer file "+file_name);
    		try {
				FileInputStream strm = new FileInputStream(act.getFilesDir() + File.separator + file_name);
				TauLayer temp = parse(strm);
				if(temp!=null){
					layers.add(temp);
					Log.i("LayerXmlParser", "Added layer from file "+file_name);
				}
				strm.close();
			} catch (Exception e) {
				Log.e("LayerXmlParser","Error parsing layer "+file_name+":"+e.getMessage());
				continue;
			}
    	}
    	permLayers = layers;
    	return;
    }
    
    //returns TauLayer described in the file of the InputStream
    //returns null if any exception encountered
    //does not close the stream
    public TauLayer parse(InputStream in) {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
            parser.setInput(in, null);
            parser.nextTag();
            return readFeed(parser);
        } catch (Exception e){
        	Log.e("LayerXmlParser","Error while parsing layer:"+e.getMessage());
            return null;
        }
    }
    
    private TauLayer readFeed(XmlPullParser parser) throws XmlPullParserException, IOException {
    	//get names of layer
    	String layerNameEn = parser.getAttributeValue(null, "en");
        String layerNameHe = parser.getAttributeValue(null, "he");
        String forDisplayS = parser.getAttributeValue(null, "display");
        boolean forDisplay;
        
        if(forDisplayS.equals("true")||forDisplayS.equals("True")||forDisplayS.equals("TRUE")){
        	forDisplay = true;
        }else if(forDisplayS.equals("false")||forDisplayS.equals("False")||forDisplayS.equals("FALSE")){
        	forDisplay = false;
        }else{
        	Log.e("LayerXmlParser","Error while parsing layer: illegal visibility status");
        	return null;
        }
        
        TauLayer lay = new TauLayer(layerNameEn,layerNameHe,forDisplay);
        //TauLayer lay = new TauLayer(layerNameEn,layerNameHe,true);

        parser.require(XmlPullParser.START_TAG, ns, "layer");
        
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String name = parser.getName();
            // Starts by looking for the item tag
            if (name.equals("item")) {
            	lay.items.add(readItem(parser));
            } else if(name.equals("image_name")){
            	lay.pic_name = readText(parser).trim();
            }else {
                skip(parser);
            }
        }
        lay.finishedPopulating(mainAct);
        return lay;
    }
	private LayerItem readItem(XmlPullParser parser) throws XmlPullParserException, IOException {
	    parser.require(XmlPullParser.START_TAG, ns, "item");
	    String en = null;
	    String he = null;
	    ArrayList<String> extra_names = new ArrayList<String>();
	    String extra_data_he = null;
	    String extra_data_en = null;
	    String extra_data_pic = null;
	    Double lat = 0.0;
	    Double lon = 0.0;
	    while (parser.next() != XmlPullParser.END_TAG) {
	        if (parser.getEventType() != XmlPullParser.START_TAG) {
	            continue;
	        }
	        String name = parser.getName();
	        //Log.i("LayerXmlParser", "name is: "+name);
	        if (name.equals("name")) {
	        	parser.require(XmlPullParser.START_TAG, ns, "name");
	        	en = parser.getAttributeValue(null, "en");
	        	//Log.i("LayerXmlParser", "en is: "+en);
	        	he = parser.getAttributeValue(null, "he");
	        	parser.next();
	        } else if (name.equals("node")) {
	        	parser.require(XmlPullParser.START_TAG, ns, "node");
	        	//Log.i("LayerXmlParser", "assigning lat and lon");
	            lat = Double.parseDouble(parser.getAttributeValue(null, "lat"));
	            lon = Double.parseDouble(parser.getAttributeValue(null, "lon"));
	            parser.next();
	        } else if (name.equals("extra_name")) {
	        	extra_names.add(parser.getAttributeValue(null, "text"));
	        	parser.next();
	        } else if (name.equals("descr_pic")) {
	        	extra_data_pic = readText(parser);
	        } else if (name.equals("descr")) {
	        	String attr = parser.getAttributeValue(null, "lang");
	            if((attr).equals("en")){
	            	extra_data_en = readText(parser).trim();
		        }
		        if((attr).equals("he")){
		          	extra_data_he = readText(parser).trim();
		        }
		        /*
		        if((attr).equals("pic")){
		          	extra_data_pic = readText(parser);
		        }*/
		        parser.require(XmlPullParser.END_TAG, ns, "descr");
		    } else {
	            skip(parser);
	        }
	    }
	    return new LayerItem(en,he, lon, lat,extra_data_en,extra_data_he,extra_names,extra_data_pic);
	}
	private String readText(XmlPullParser parser) throws IOException, XmlPullParserException {
        String result = "";
        if (parser.next() == XmlPullParser.TEXT) {
            result = parser.getText();
            parser.nextTag();
        }
        return result;
    }
    private void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        if (parser.getEventType() != XmlPullParser.START_TAG) {
            throw new IllegalStateException();
        }
        int depth = 1;
        while (depth != 0) {
            switch (parser.next()) {
            case XmlPullParser.END_TAG:
                depth--;
                break;
            case XmlPullParser.START_TAG:
                depth++;
                break;
            }
        }
     }

	public List<TauLayer> getDisplayedLayers() {
		ArrayList<TauLayer> res = new ArrayList<TauLayer>();
		for(TauLayer lay : permLayers){
			if(lay.display){
				res.add(lay);
			}
		}
		return res;
	}
}
